<script lang="ts">
  import OtoSwiper from '@/components/common/oto-swiper.vue';
  import OtoButton from '@/components/common/oto-button.vue';
  import { HOME_PAGE_ICON_PATHS } from '@/constants/path';
  import { ROUTER_PATHS, useRouter } from '@/constants/router';
  import { defineComponent, ref, reactive, computed } from '@vue/composition-api';
  import { toTabbar, toPage } from '@/utils/router';
  import { UserModule } from '@/store/modules/user.module';
  import { useStore } from '@/store';
  import { useGoEasyListen, useLoadConversations } from '@/hooks/go-easy.hooks';
  import { onShow } from '@/hooks/uniapp-composition-hooks';
  import {
    addStudyMatchScore,
    cancelStudyMatch,
    getStudyMatchNeed,
    getStudyMatchStatus,
    getTaskList,
    getUserMessage,
    IntegralTaskResponse,
    StudyMatchStatusResponse
  } from '@/api/study-match';
  import { Message } from '@/libs';
  import { FINISH_STATUS, RECORD_STATUS } from '@/enum/common';
  import { STUDY_MATCH_STATUS, TASK_LIST } from '@/enum/study-match';

  export default defineComponent({
    components: {
      OtoSwiper,
      OtoButton
    },
    setup() {
      const router = useRouter();
      try {
        useGoEasyListen();
      } catch (error) {
        console.log(error);
      }
      const result = ref<StudyMatchStatusResponse>({
        code: 0
      });

      const taskListByApi = ref<IntegralTaskResponse[]>([]);
      const taskMap = ref<Record<TASK_LIST, FINISH_STATUS>>({
        [TASK_LIST.EVERY_DAY]: FINISH_STATUS.NOT_FINISHED,
        [TASK_LIST.RUN]: FINISH_STATUS.NOT_FINISHED,
        [TASK_LIST.PUBLISH]: FINISH_STATUS.NOT_FINISHED
      });
      function getStatus() {
        getStudyMatchStatus().then((res) => {
          result.value = res.data;
          getTaskList(result.value.id || 0).then((res) => {
            taskListByApi.value = res.data;
            taskListByApi.value.forEach((item) => {
              if (taskMap.value[item.taskType]) {
                taskMap.value[item.taskType] = item.status;
              }
            });
          });
        });
      }
      onShow(() => {
        useLoadConversations();
        getStatus();
      });
      const userModule = useStore(UserModule);
      const pages = reactive(ROUTER_PATHS);
      const icons = ref(HOME_PAGE_ICON_PATHS);
      const entrance = ref([
        {
          url: pages.WORD,
          icon: HOME_PAGE_ICON_PATHS.WORD,
          text: '单词'
        },
        {
          url: pages.SQUARE,
          icon: HOME_PAGE_ICON_PATHS.DYNAMIC,
          text: '动态'
        },
        {
          url: pages.MESSAGE,
          icon: HOME_PAGE_ICON_PATHS.MESSAGE,
          text: '消息'
        }
      ]);

      const carousel = ref([
        {
          link: '',
          path: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F811%2F091214203241%2F140912203241-2-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1654216220&t=47620ac34f1e9b4e70e0cf35ad5b5257'
        }
      ]);

      const partner = ref({
        isFit: false,
        task: 0,
        integral: 0,
        my: {
          name: userModule.getUserInfo.nickName,
          avartar: userModule.getUserInfo.avatarUrl
        },
        fit: {
          name: '暂未匹配',
          avartar: 'none'
        }
      });

      function toPreferences() {
        getUserMessage().then(async (res) => {
          if (res.data) {
            toPage(pages.PREFERENCES);
          } else {
            await Message.warning('请先填写信息', {
              duration: 500
            });
            toPage(pages.PERSONAL_USER_MESSAGE);
          }
        });
      }
      const submitStudyMatchNeedStatus = ref(false);

      function getSubmitStudyMatchNeedStatus() {
        getStudyMatchNeed().then((res) => {
          if (res.data && res.data?.status === RECORD_STATUS.SHOW) {
            submitStudyMatchNeedStatus.value = true;
            return;
          }
          submitStudyMatchNeedStatus.value = false;
        });
      }

      function toCancelStudyMatch() {
        cancelStudyMatch().then(async (res) => {
          console.log(res);
          submitStudyMatchNeedStatus.value = false;
          getStatus();
          await Message.success('取消报名成功', {
            duration: 1000
          });
        });
      }

      function toInputInvitationCode() {
        router.navigateTo({
          url: ROUTER_PATHS.INVITATION_CODE,
          params: {
            type: 1 // 1表示是输入别人的邀请码
          }
        });
      }

      function toCreateInvitationCode() {
        router.navigateTo({
          url: ROUTER_PATHS.INVITATION_CODE,
          params: {
            type: 2 // 1表示生成自己的邀请码
          }
        });
      }
      const tabIndex = ref(0);
      const taskList = ref([
        {
          text: '每日签到'
        },
        {
          text: '运动签到'
        }
      ]);

      function clickTab(index: number) {
        tabIndex.value = index;
      }
      // #ifdef MP-WEIXIN
      wx.cloud.init();
      // #endif
      const step = ref(0);

      function getStep() {
        // #ifdef MP-WEIXIN
        wx.getWeRunData({
          success(res) {
            // 或拿 cloudID 通过云调用直接获取开放数据
            const cloudID = res.cloudID;
            wx.cloud
              .callFunction({
                name: 'nn',
                data: {
                  weRunData: wx.cloud.CloudID(cloudID) // 这个 CloudID 值到云函数端会被替换
                }
              })
              .then((res) => {
                console.log(res);
                step.value = (res.result as any).weRunData.data.stepInfoList[
                  (res.result as any).weRunData.data.stepInfoList.length - 1
                ].step;
              });
          }
        });
        // #endif
        // #ifndef MP-WEIXIN
        // 修复非小程序平台不存在获取用户获取步数的api问题
        setTimeout(() => {
          step.value = 3000;
        }, 200);
        // #endif
      }

      const stepMax = ref(10000);
      const stepPersent = computed(() => {
        return step.value / stepMax.value;
      });

      function makeFinishForSignIn(num: number) {
        addStudyMatchScore({
          num: num,
          type: TASK_LIST.EVERY_DAY,
          matchId: result.value.id || 0
        }).then((res) => {
          console.log(res);
          Message.success('签到成功');
        });
      }

      function makeFinishForMotion(num: number) {
        if (step.value < stepMax.value) {
          return Message.other('请先完成任务哦～');
        }
        addStudyMatchScore({
          num: num,
          type: TASK_LIST.RUN,
          matchId: result.value.id || 0
        }).then((res) => {
          console.log(res);
          Message.success('打卡成功');
        });
      }

      function finish() {
        router.navigateTo({
          url: ROUTER_PATHS.DYNAMIC_PUBLISH
        });
      }

      onShow(() => {
        getSubmitStudyMatchNeedStatus();
        getStep();
      });

      return {
        taskMap,
        TASK_LIST,
        FINISH_STATUS,
        taskListByApi,
        HOME_PAGE_ICON_PATHS,
        step,
        stepMax,
        stepPersent,
        taskList,
        tabIndex,
        carousel,
        entrance,
        pages,
        icons,
        partner,
        submitStudyMatchNeedStatus,
        result,
        STUDY_MATCH_STATUS,
        makeFinishForSignIn,
        makeFinishForMotion,
        clickTab,
        toTabbar,
        toPage,
        toPreferences,
        toCancelStudyMatch,
        toInputInvitationCode,
        toCreateInvitationCode,
        finish
      };
    }
  });
</script>

<template>
  <view class="home">
    <view class="carousel">
      <oto-swiper
        :indicatorDotsInswiper="true"
        :swiperRealStyle="{ height: '300rpx' }"
        :list="carousel"
        :imageCustom="true"
        :circular="true"
        :interval="5000"
      >
        <template v-slot:image-item="{ item }">
          <image @click.stop="toPage(item.link)" style="width: 100%; height: 100%" :src="item.path" mode="aspectFill" />
        </template>
      </oto-swiper>
    </view>
    <view class="entrance">
      <view class="entrance-item" v-for="(item, index) in entrance" :key="index" @click.stop="toTabbar(item.url)">
        <image class="entrance-item-icon" :src="item.icon" />
        <view class="entrance-item-text">{{ item.text }}</view>
      </view>
    </view>
    <view class="study-partner">
      <view class="study-title">学习伴侣</view>
      <template v-if="result.code === STUDY_MATCH_STATUS.MATCHED">
        <view class="partner-message">
          <view class="user">
            <view class="user-item">
              <image class="user-avartar" :src="result.matchOneUserInfo.avatarUrl" />
              <view class="usrer-nick-name">{{ result.matchOneUserInfo.nickName }}</view>
            </view>
            <image class="fit-icon" :src="icons.FIT" />
            <view class="user-item">
              <image class="user-avartar" :src="result.matchTwoUserInfo.avatarUrl" />
              <view class="usrer-nick-name">{{ result.matchTwoUserInfo.nickName }}</view>
            </view>
          </view>

          <view class="tips today-task">
            <text class="title">今日完成任务总数</text>
            <text class="number">{{ taskListByApi.length }}</text>
          </view>
          <view class="tips today-integral">
            <text class="title">当前积分</text>
            <text class="number">{{ result.integral }}</text>
          </view>
        </view>
        <view class="oto-line"></view>
        <view class="tabs">
          <view
            class="tabs-item"
            :class="{
              active: tabIndex === 0
            }"
            @click.stop="clickTab(0)"
            >任务列表</view
          >
          <view
            class="tabs-item"
            :class="{
              active: tabIndex === 1
            }"
            @click.stop="clickTab(1)"
            >其他</view
          >
        </view>
        <view class="tabs-body">
          <view class="task-list">
            <view class="always">日常任务</view>
            <view class="task-list-body">
              <view class="task-list-item">
                <image class="icons" :src="HOME_PAGE_ICON_PATHS.EVERY_DAY" />
                <view class="text">
                  <view class="top">每日签到</view>
                  <view class="top-right">
                    <view class="images">
                      <image class="left" :src="result.matchOneUserInfo.avatarUrl" />
                      <image class="right" :src="result.matchTwoUserInfo.avatarUrl" />
                    </view>
                  </view>
                  <view class="bottom">
                    <view class="left">积分:20 </view>
                    <view class="right finish-button" v-if="taskMap[TASK_LIST.EVERY_DAY] === FINISH_STATUS.FINISHED"
                      >已签到</view
                    >
                    <view
                      class="right finish-button"
                      @click.stop="makeFinishForSignIn(20)"
                      v-if="taskMap[TASK_LIST.EVERY_DAY] === FINISH_STATUS.NOT_FINISHED"
                      >签到</view
                    >
                  </view>
                </view>
              </view>
              <view class="task-list-item">
                <image class="icons" :src="HOME_PAGE_ICON_PATHS.RUN" />
                <view class="text">
                  <view class="top">运动打卡</view>
                  <view class="top-right">
                    <view class="images">
                      <image class="left" :src="result.matchOneUserInfo.avatarUrl" />
                      <image class="right" :src="result.matchTwoUserInfo.avatarUrl" />
                    </view>
                    <view class="tips">{{ step + '/' + stepMax }}</view>
                  </view>
                  <view class="bottom">
                    <view class="left">积分:30 </view>
                    <view class="right finish-button" v-if="taskMap[TASK_LIST.RUN] === FINISH_STATUS.FINISHED"
                      >已打卡</view
                    >
                    <view
                      class="right finish-button"
                      @click.stop="makeFinishForMotion(30)"
                      v-if="taskMap[TASK_LIST.RUN] === FINISH_STATUS.NOT_FINISHED"
                      >打卡</view
                    >
                  </view>
                </view>
              </view>
            </view>
            <view class="special"> 特殊任务 </view>
            <view class="task-list-body">
              <view class="task-list-item">
                <image class="icons" :src="HOME_PAGE_ICON_PATHS.QZONE" />
                <view class="text">
                  <view class="top">发布一条社区动态</view>
                  <view class="top-right">
                    <view class="images">
                      <image class="left" :src="result.matchOneUserInfo.avatarUrl" />
                      <image class="right" :src="result.matchTwoUserInfo.avatarUrl" />
                    </view>
                  </view>
                  <view class="bottom">
                    <view class="left">积分:10 </view>
                    <view class="right finish-button" v-if="taskMap[TASK_LIST.RUN] === FINISH_STATUS.FINISHED"
                      >已完成</view
                    >
                    <view
                      class="right finish-button"
                      @click.stop="finish(10)"
                      v-if="taskMap[TASK_LIST.RUN] === FINISH_STATUS.NOT_FINISHED"
                      >去完成</view
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <template>
        <view v-if="result.code === STUDY_MATCH_STATUS.NOT_MATCH" class="need-fit">
          <view class="fit-gif-box">
            <image class="fit-gif" mode="heightFix" :src="icons.FIT_GIF" />
          </view>
          <view class="fit-text">
            <view class="title">匹配学习伴侣</view>
            <view class="content">可以进行匹配一起学习和玩耍的小伙伴哦～</view>
          </view>
          <view class="fit-button">
            <oto-button @click.stop="toPreferences(pages.PREFERENCES)"> 开始匹配 </oto-button>
            <view class="other-button">
              <text @click.stop="toInputInvitationCode" class="have-code">我有邀请码 > </text>
              <text @click.stop="toCreateInvitationCode">生成邀请码 > </text>
            </view>
          </view>
        </view>
        <view class="fit-now" v-if="result.code === STUDY_MATCH_STATUS.MATCHING">
          <view class="leidaAll">
            <view class="leidaContent">
              <view class="leida">
                <view class="leiquanTx" style="overflow: hidden">
                  <view class="leidaPoint"></view>
                  <view class="leidaPoint" style="left: 60%; top: 20%"></view>
                  <view class="leidaPoint" style="left: 70%; top: 80%"></view>
                  <view class="leiquanTxOne" style="width: 75%; height: 75%"> </view>
                  <view class="leiquanTxOne" style="width: 50%; height: 50%"> </view>
                  <view class="touxiang" style="width: 10vw; height: 10vw; border-radius: 10vw; overflow: hidden">
                    <open-data type="userAvatarUrl"></open-data>
                  </view>
                </view>
                <view class="leidaquan"></view>
              </view>
            </view>
            <view class="leidaBtn">
              <view class="leidaBtnText">
                <text>每星期5的12:00系统自动匹配，耐心等待哦，这个时间可以先背背单词</text>
              </view>
              <view class="leidaInput" @click.stop="toCancelStudyMatch">取消报名</view>
            </view>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<style lang="scss" scoped>
  .oto-line {
    height: 18rpx;
    background: #fbfbfb;
  }
  .home {
    .carousel {
      width: 670rpx;
      margin: 0 auto;
    }
    .entrance {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 100rpx 0 100rpx;

      .entrance-item {
        .entrance-item-icon {
          width: 100rpx;
          height: 100rpx;
        }

        .entrance-item-text {
          text-align: center;
          margin-top: 8rpx;
          font-family: 'PingFang SC';
          font-style: normal;
          font-weight: 400;
          font-size: 28rpxpx;
          line-height: 40rpx;
        }
      }
    }

    .study-partner {
      padding-left: 40rpx;
      padding-right: 40rpx;

      .study-title {
        font-family: 'PingFang SC';
        font-style: normal;
        font-weight: 500;
        font-size: 32rpx;
        line-height: 44rpx;
        color: #000000;
        margin-top: 40rpx;
      }

      .partner-message {
        margin-top: 22rpx;
        min-height: 278rpx;

        .user {
          display: flex;
          justify-content: center;
          align-items: center;

          .user-item {
            text-align: center;
            .user-avartar {
              width: 96rpx;
              height: 96rpx;
              border-radius: 50%;
              background-color: antiquewhite;
            }
            .user-nick-name {
              margin-top: 8rpx;
              font-family: 'PingFang SC';
              font-style: normal;
              font-weight: 400;
              font-size: 28rpx;
              line-height: 40rpx;
              /* identical to box height */

              text-align: center;
              color: #000000;
            }
          }

          .fit-icon {
            width: 80rpx;
            height: 80rpx;
            margin-left: 52rpx;
            margin-right: 52rpx;
          }
        }

        .tips {
          font-family: 'PingFang SC';
          font-style: normal;
          font-weight: 600;
          font-size: 24rpx;
          line-height: 34rpx;
          /* identical to box height */

          color: #c9c7c6;

          .title {
            margin-right: 22rpx;
          }

          .number {
            font-family: 'PingFang SC';
            font-style: normal;
            font-weight: 600;
            font-size: 28rpx;
            line-height: 40rpx;
            /* identical to box height */

            color: #ed7773;
          }
        }

        .today-task {
          margin-top: 18rpx;
        }
      }

      .tabs {
        padding-top: 30rpx;
        padding-bottom: 20rpx;
        display: flex;

        .tabs-item {
          font-size: 26rpx;
          color: rgb(180, 179, 179);
          font-weight: bold;

          &:not(:first-child) {
            margin-left: 90rpx;
          }
        }

        .active {
          font-size: 28rpx;
          color: #000;
        }
      }

      .tabs-body {
        .always {
          font-size: 4vw;
          font-weight: bold;
          color: #363636;
          margin-bottom: 30rpx;
        }
        .special {
          font-size: 4vw;
          font-weight: bold;
          color: #363636;
          margin-bottom: 30rpx;
        }

        .task-list {
          padding-bottom: 50rpx;

          .task-list-item {
            display: flex;
            margin-bottom: 30rpx;

            .icons {
              width: 150rpx;
              height: 150rpx;
              background: #c9c7c6;
            }

            .text {
              position: relative;
              flex: 1;
              display: flex;
              flex-direction: column;
              margin-left: 20rpx;
              margin-top: 5rpx;
              .top {
                font-size: 3.8vw;
                font-weight: bold;
              }

              .top-right {
                position: absolute;
                right: 0;
              }
              .images {
                image {
                  width: 50rpx;
                  height: 50rpx;
                  border-radius: 50%;
                }
                .left {
                  margin-right: -20rpx;
                }
              }
              .tips {
                font-weight: 400;
                font-size: 3vw;
              }

              .bottom {
                flex: 1;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                padding-bottom: 10rpx;
                border-bottom: 3rpx solid #f3f3f3;

                .finish-button {
                  font-size: 3.5vw;
                  width: 16.5vw;
                  height: 6.5vw;
                  border-radius: 3vw;
                  background-color: #fdd745;
                  color: #444444;
                  margin-left: 5vw;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                }
              }
            }
          }
        }
      }

      .need-fit {
        .fit-gif-box {
          display: flex;
          justify-content: center;
          .fit-gif {
            height: 260rpx;
          }
        }

        .fit-text {
          margin-top: 30rpx;
          text-align: center;
          color: #aaa;
          .title {
            font-size: 36rpx;
          }

          .content {
          }
        }

        .fit-button {
          margin-top: 65rpx;

          .other-button {
            margin-top: 20rpx;
            text-align: center;
            color: #6b6b6b;

            .have-code {
              margin-right: 100rpx;
            }
          }
        }
      }
    }

    .leidaquan {
      position: absolute;
      left: -100%;
      top: -100%;
      width: 150%;
      height: 150%;
      transform-origin: 100% 100%;
      background: linear-gradient(185deg, rgb(255, 80, 138) 40%, rgba(255, 255, 255, 0) 90%);
      animation: rotation 3s linear infinite;
      -webkit-animation: rotation 3s linear infinite;
      z-index: 3;
    }

    @keyframes rotation {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
    @keyframes point {
      0% {
        transform: scale(1.2);
        background-color: #f75988;
      }
      100% {
        transform: scale(0.8);
        background-color: #f04f7f54;
      }
    }
    .leidaAll {
      width: 100%;
      height: 100%;
    }
    .leidaContent {
      width: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .leida {
      border: 2px solid #fcdfea;
      width: 40vw;
      height: 40vw;
      border-radius: 40vw;
      overflow: hidden;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .leiquanTx {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
    }
    .leiquanTx image {
      width: 20vw;
      height: 20vw;
      border-radius: 50%;
      border: 1vw solid #fff;
    }
    .leidaPoint {
      width: 2vw;
      height: 2vw;
      background-color: #f04f80;
      position: absolute;
      left: 10%;
      border-radius: 50%;
      z-index: 2;
      box-shadow: 2px 2px 10px 2px #ffbbd4;
      animation: point 1s linear infinite alternate;
    }
    .leiquanTxOne {
      border: 2px solid #fcdfea;
      position: absolute;
      border-radius: 50%;
    }

    .leidaBtn {
      width: 100%;
    }
    .leidaBtnText {
      width: 70%;
      padding: 5vw;
      box-shadow: 2rpx 5rpx 2vw rgba(151, 150, 150, 0.2);
      margin: 0 auto;
      color: #444;
    }

    .leidaInput {
      width: 70%;
      height: 7vh;
      margin: 20rpx auto auto auto;
      border-radius: 3.5vh;
      background-color: rgba(255, 80, 138, 0.548);
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      font-size: 4.5vw;
    }
  }
</style>
